﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using LOGISTCBUS.Entities;
using LOGISTCBUS.DAO;
using System.Configuration;
using System.IO;
using System.Web.Script.Serialization;

namespace LOGISTCBUS.WebUI.Controllers
{
    [HandleError(View = "Error")]
    public class TripController : Controller
    {
        public ActionResult Index()
        {
            var user = (User)this.Session["user"];
            if (user == null)
                return RedirectToAction(@"LogOut", @"Account");
            return View();
        }

        public ActionResult Edit(int? id)
        {
            var userLogged = (User)this.Session["user"];
            if (userLogged == null)
                return RedirectToAction(@"LogOut", @"Account");

            if (id.HasValue)
            {
                var trip = new TripDAO().selectById(Convert.ToInt32(id));
                this.ViewData[@"trip"] = trip == null ? new Trip() : trip;
            }

            return View();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public JsonResult Save(int id)
        {
            var t = id > 0 ? new TripDAO().selectById(id) : new Trip();
            var aux = true;

            #region trip
            t.Code = !String.IsNullOrEmpty(Request.Params["code"]) ? Request.Params["code"] : null;
            t.Origin = !String.IsNullOrEmpty(Request.Params["origin"]) ? Request.Params["origin"] : null;
            t.Destination = !String.IsNullOrEmpty(Request.Params["destination"]) ? Request.Params["destination"] : null;
            t.Description = !String.IsNullOrEmpty(Request.Params["description"]) ? Request.Params["description"] : null;
            var beginDate = !String.IsNullOrEmpty(Request.Params["begin_date"]) ? DateTime.Parse(Request.Params["begin_date"]) : new Nullable<DateTime>();
            if (beginDate.HasValue)
            {
                var beginTime = !String.IsNullOrEmpty(Request.Params["begin_time"]) ? TimeSpan.Parse(Request.Params["begin_time"]) : new TimeSpan();
                var date = Convert.ToDateTime(beginDate);
                beginDate = date + beginTime;
                t.BeginDate = beginDate;
            }
            var endDate = !String.IsNullOrEmpty(Request.Params["end_date"]) ? DateTime.Parse(Request.Params["end_date"]) : new Nullable<DateTime>();
            if (endDate.HasValue)
            {
                var endTime = !String.IsNullOrEmpty(Request.Params["end_time"]) ? TimeSpan.Parse(Request.Params["end_time"]) : new TimeSpan();
                var date = Convert.ToDateTime(endDate);
                endDate = date + endTime;
                t.EndDate = endDate;
            }

            if (t.Id > 0)
                aux = new TripDAO().update(t);
            else
                aux = new TripDAO().insert(t);
            #endregion

            #region vehicles
            var lstVehicles = new VehicleTripDAO().selectByTrip(t.Id);
            if (lstVehicles != null && lstVehicles.Count > 0)
            {
                foreach (var vt in lstVehicles)
                    aux = new VehicleTripDAO().delete(vt);
            }

            var vehicles = Request.Form["vehicles"].Split(new String[] { ";" }, StringSplitOptions.RemoveEmptyEntries).ToList();
            if (vehicles != null && vehicles.Count > 0)
            {
                foreach (var v in vehicles)
                {
                    if (!String.IsNullOrEmpty(v))
                    {
                        var vt = new VehicleTrip()
                        {
                            Trip = t,
                            Vehicle = new Vehicle() { Id = Convert.ToInt32(v) }
                        };
                        aux = new VehicleTripDAO().insert(vt);
                    }
                }
            }
            #endregion

            #region students
            var lstStudents = new StudentTripDAO().selectByTrip(t.Id);
            if (lstStudents != null && lstStudents.Count > 0)
            {
                foreach (var st in lstStudents)
                    aux = new StudentTripDAO().delete(st);
            }

            var students = Request.Form["students"].Split(new String[] { ";" }, StringSplitOptions.RemoveEmptyEntries).ToList();
            if (students != null && students.Count > 0)
            {
                foreach (var s in students)
                {
                    if (!String.IsNullOrEmpty(s))
                    {
                        var st = new StudentTrip()
                        {
                            Trip = t,
                            Student = new Student() { Id = Convert.ToInt32(s) }
                        };
                        aux = new StudentTripDAO().insert(st);
                    }
                }
            }
            #endregion

            #region customers
            var lstCustomers = new CustomerTripDAO().selectByTrip(t.Id);
            if (lstCustomers != null && lstCustomers.Count > 0)
            {
                foreach (var c in lstCustomers)
                    aux = new CustomerTripDAO().delete(c);
            }

            var customers = Request.Form["customers"].Split(new String[] { ";" }, StringSplitOptions.RemoveEmptyEntries).ToList();
            if (customers != null && customers.Count > 0)
            {
                foreach (var c in customers)
                {
                    if (!String.IsNullOrEmpty(c))
                    {
                        var st = new CustomerTrip()
                        {
                            Trip = t,
                            Customer = new Customer() { Id = Convert.ToInt32(c) }
                        };
                        aux = new CustomerTripDAO().insert(st);
                    }
                }
            }
            #endregion

            #region documents
            var lstDocuments = new DocumentDAO().selectByTrip(t.Id);
            if (lstDocuments != null && lstDocuments.Count > 0)
            {
                foreach (var d in lstDocuments)
                    aux = new DocumentDAO().delete(d);
            }

            var documents = !String.IsNullOrEmpty(Request.Form["documents"]) ? Request.Form["documents"].Split(new String[] { ";" }, StringSplitOptions.RemoveEmptyEntries) : new String[] { "" };
            if (documents != null && documents.Length > 0)
            {
                foreach (var d in documents)
                {
                    if (!String.IsNullOrEmpty(d))
                    {
                        var doc = new Document()
                        {
                            Name = d.Trim(),
                            Date = DateTime.Now,
                            Trip = t
                        };
                        aux = new DocumentDAO().insert(doc);
                    }
                }
            }
            #endregion

            var obj = new
            {
                success = aux,
                message = "Viagem salva com sucesso!"
            };

            return Json(obj);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public JsonResult Search()
        {
            var page = String.IsNullOrEmpty(Request.Params[@"page"]) ? 1 : Convert.ToInt32(Request.Params[@"page"]);
            var origin = String.IsNullOrEmpty(Request.Params[@"origin"]) ? string.Empty : Request.Params[@"origin"].ToString();
            var destination = String.IsNullOrEmpty(Request.Params[@"destination"]) ? string.Empty : Request.Params[@"destination"].ToString();
            var pageSize = MvcApplication.pageSize;
            var trips = new TripDAO().select(origin, destination, page, pageSize);
            var count = new TripDAO().getCount(origin, destination);
            var totalPages = (count < pageSize) ? 1 : Math.Ceiling(Convert.ToDecimal(count) / pageSize);
            var lst = new List<object>();

            foreach (var t in trips)
            {
                lst.Add(new
                {
                    Id = t.Id,
                    Code = t.Code,
                    Origin = t.Origin,
                    Destination = t.Destination,
                    Description = t.Description
                });
            }

            var obj = new
            {
                data = lst,
                currpage = page,
                totalpages = totalPages,
                totalrecords = count
            };

            return Json(obj);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public JsonResult Delete()
        {
            var id = String.IsNullOrEmpty(Request.Params[@"id"]) ? 0 : Convert.ToInt32(Request.Params[@"id"]);
            var page = String.IsNullOrEmpty(Request.Params[@"page"]) ? 1 : Convert.ToInt32(Request.Params[@"page"]);
            var aux = true;

            if (id > 0)
            {
                var t = new Trip() { Id = id };
                aux = new TripDAO().delete(t);
            }

            var obj = new
            {
                Message = "Registro removido com sucesso!",
                Success = aux,
                Page = page
            };

            return Json(obj);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public JsonResult DeleteAll()
        {
            var values = Request.Form["ids"].Split(new String[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
            var aux = true;

            var lst = new List<Trip>();
            foreach (var val in values)
                if (!String.IsNullOrEmpty(val))
                    lst.Add(new Trip() { Id = Convert.ToInt32(val) });
            aux = new TripDAO().delete(lst);

            var obj = new
            {
                Message = "Registro(s) removido(s) com sucesso!",
                Success = aux
            };

            return Json(obj);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public JsonResult DeleteFile()
        {
            var aux = false;
            var idTrip = String.IsNullOrEmpty(Request.Params[@"idTrip"]) ? 0 : Convert.ToInt32(Request.Params[@"idTrip"]);
            var documents = !String.IsNullOrEmpty(Request.Form["documents"]) ? Request.Form["documents"].Split(new String[] { ";" }, StringSplitOptions.RemoveEmptyEntries) : new String[] { "" };
            if (documents != null && documents.Length > 0)
            {
                foreach (var d in documents)
                {
                    if (!String.IsNullOrEmpty(d))
                    {
                        var doc = new DocumentDAO().selectByName(d, idTrip);
                        if (doc != null)
                        {
                            var urlFiles = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Files");
                            var fileName = Path.Combine(urlFiles, doc.Name);
                            if (System.IO.File.Exists(fileName))
                                System.IO.File.Delete(fileName);
                            aux = new DocumentDAO().delete(doc);
                        }
                        else
                        {
                            var urlFiles = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Files");
                            var fileName = Path.Combine(urlFiles, d);
                            if (System.IO.File.Exists(fileName))
                            {
                                System.IO.File.Delete(fileName);
                                aux = true;
                            }
                        }
                    }
                }
            }

            var obj = new
            {
                Message = "Documento(s) removido(s) com sucesso!",
                Success = aux
            };

            return Json(obj);
        }
    }
}
